package common

import (
	"fmt"
	"strings"
)

type reply struct {
	Code    int         `json:"State"`
	Message string      `json:"Message"`
	Data    interface{} `json:"Data"`
}

type clientError struct {
	err  error
	code int
}

func newClientError(format string, v ...interface{}) clientError {
	return clientError{err: fmt.Errorf(format, v...), code: 400}
}

func newClientErrorV2(code int, format string, v ...interface{}) clientError {
	return clientError{err: fmt.Errorf(format, v...), code: code}
}

func newClientErrorV3(e error) clientError { return clientError{err: e, code: 400} }

func (ce clientError) Error() string {
	return ce.err.Error()
}

func ErrReply(err error) reply {
	if v, ok := err.(clientError); ok {
		return reply{Code: v.code, Message: err.Error()}
	}

	msg := err.Error()
	lowerMsg := strings.ToLower(msg)
	if strings.Contains(lowerMsg, "failed to find") || strings.Contains(lowerMsg, "not found") {
		return reply{Code: 404, Message: msg}
	}
	if strings.Contains(lowerMsg, "addtransaction: exist") {
		return reply{Code: 400, Message: msg}
	}
	return reply{Code: 500, Message: msg}
}
